package com.jing.weibo.controller.user;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.DataCons;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.RuleType;
import com.jing.system.utils.StringUtil;
import com.jing.weibo.pojo.pb.PbUserTypeSeat;
import com.jing.weibo.pojo.system.Rule;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.pb.PbUserTypeSeatService;
import com.jing.weibo.service.system.StationletterService;
import com.jing.weibo.service.user.UserCwMpService;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.service.user.UserMpService;
import com.jing.weibo.ws.sina.FriendshipsService;

/**
 * 用户信息中心的Controller
 * @author jing.yue
 * @version 2012/11/18 1.0.0
 */
@Controller
public class UserCenterController extends BaseController {

	private static final Logger logger = Logger.getLogger(UserCenterController.class);

	@Autowired
	private StationletterService stationletterService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private PbUserTypeSeatService pbUserTypeSeatService;
	@Autowired
	private UserMpService userMpService;
	@Autowired
	private UserCwMpService userCwMpService;
	@Autowired
	private FriendshipsService friendshipsService;

	/**
	 * 修改用户是否开启互粉
	 * @return
	 */
	@RequestMapping(value = "/userCenter/json/isOpenMp")
	@ResponseBody
	public ModelMap isOpenMp(HttpServletRequest request, Integer isopenmp) {
		logger.info("修改用户是否开启互粉");
		String result = null;
		String weiboMsg = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			userInfo.setIsopenmp(isopenmp);
			userInfoService.updateUserInfoIsopenmp(userInfo);

			setSessionUser(request, userInfo);
			result = SUCCESS;

			//为关闭互粉 将该用户的所有位置置为丢失
			if(isopenmp.intValue() == 0) {
				PbUserTypeSeat pbUserTypeSeat = new PbUserTypeSeat();
				pbUserTypeSeat.setUsername(userInfo.getUsername());
				pbUserTypeSeatService.updatePbUserTypeSeatUsernameToLog(pbUserTypeSeat);
				//根据用户名删除可互粉用户信息
				userMpService.deleteByUsername(userInfo.getUsername());
			}
			else {
				//保存可互粉用户信息
				if(userMpService.findByUsername(userInfo.getUsername()) == null) {
					userMpService.saveUserMp(userInfo);
				}
			}
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e), e);
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("修改用户是否开启互粉异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 修改用户是否开启同城互粉
	 * @return
	 */
	@RequestMapping(value = "/userCenter/json/isOpenCwMp")
	@ResponseBody
	public ModelMap isOpenCwMp(HttpServletRequest request, Integer isopencwmp) {
		logger.info("修改用户是否开启同城互粉");
		String result = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			userInfo.setIsopencitywidemp(isopencwmp);
			userInfoService.updateUserInfoIsopencwmp(userInfo);

			setSessionUser(request, userInfo);
			result = SUCCESS;

			//为关闭同城互粉 将该用户的同城互粉表中的数据删除
			if(isopencwmp.intValue() == 0) {
				//根据用户名删除可同城互粉用户信息
				userCwMpService.deleteByUsername(userInfo.getUsername());
			}
			else {
				//保存可同城互粉用户信息
				if(userCwMpService.findByUsername(userInfo.getUsername()) == null) {
					userCwMpService.saveUserCwMp(userInfo);
				}
			}
		} catch (Exception e) {
			logger.error("修改用户是否开启同城互粉异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 获取用户未处理的记录数
	 * @return
	 */
	@RequestMapping(value = "/userCenter/json/findUnDealInfoCount")
	@ResponseBody
	public ModelMap findUnDealInfoCount(HttpServletRequest request) {
		String result = null;
		ModelMap modelMap = new ModelMap();
		UserInfo userInfo = getSessionUser(request);
			try {
				Integer unDealInfoCount = stationletterService.findUnStationletterCount(userInfo.getUsername());
				modelMap.put("unReadStationletterCount", unDealInfoCount);
				result = SUCCESS;
			} catch (Exception e) {
				logger.error(userInfo.getNickname() + ": 获取最近登录的用户列表异常!", e);
				result = ERROR;
			}
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 跳转到邀请用户列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/toInviteUserManager")
	public String toInviteUserManager(HttpServletRequest request) {
		return "user/system/inviteuser_manager";
	}

	/**
	 * 分页获取用户邀请的列表
	 * @return
	 */
	@RequestMapping(value = "/userCenter/json/findInviteFriendInfo")
	@ResponseBody
	public ModelMap findInviteFriendInfo(HttpServletRequest request, UserInfo user) {
		String result = null;
		Map<String, Object> map = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			if(StringUtil.isEmpty(user.getUsername())) {
				user.setUsername(userInfo.getUsername());
			}
			map = userInfoService.findInviteFriendInfo(user);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 获取用户邀请的列表异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 获取邀请排行榜的列表[前几位]
	 * @return
	 */
	@RequestMapping(value = "/userCenter/json/findTopInviteFriendInfo")
	@ResponseBody
	public ModelMap findTopInviteFriendInfo(HttpServletRequest request) {
		String result = null;
		List<UserInfo> list = null;
		Rule rule = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			rule = DataCons.ruleMap.get(RuleType.TYPE_INVITE_USERS.getCode());
			list = userInfoService.findTopInviteFriendInfo(SystemCons.INVITE_FRIEND_TOP_NUM);
			result = SUCCESS;
		} catch (Exception e) {
			logger.error(userInfo.getNickname() + ": 获取邀请排行榜的列表[前几位]异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", list);
		modelMap.put("rule", rule);
		modelMap.put("result", result);
		return modelMap;
	}

	/**
	 * 关注用户
	 * @param opterType	类型[attInvite邀请排行榜关注]
	 * @return
	 */
	@RequestMapping(value = "/userCenter/json/attentionUser")
	@ResponseBody
	public ModelMap attentionUser(HttpServletRequest request, String uids, String opterType) {
		String result = null;
		Integer errorWeiboCode = null;
		StringBuffer errorWeiboMsg = new StringBuffer();
		UserInfo userInfo = getSessionUser(request);
		int count = 0;
		int errorCount = 0;
		String[] uidArr = uids.split(",");
		for (String uid : uidArr) {
			if(StringUtil.isEmpty(uid)) {
				continue;
			}
			try {
				friendshipsService.createFriendshipsById(uid, userInfo.getToken());
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口关注[").append(uid).append("]用户出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
				errorWeiboCode = e.getErrorCode();
				errorCount ++;
			} catch (Exception e) {
				logger.error("关注用户异常!", e);
				errorCount ++;
			}

			//处理邀请排行关注的妞币信息
			if("attInvite".equals(opterType)) {

			}
			count ++;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("errorWeiboCode", errorWeiboCode);
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		return modelMap;
	}
}